<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ace Editor 自动补全示例</title>
    <!-- 引入 Ace Editor 的 CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ext-language_tools.js"></script>
</head>
<body>
    <div id="editor" style="height: 500px; width: 100%;"></div>

    <script>
        // 初始化 Ace Editor
        const editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/sql");

        // 启用自动补全
        ace.require("ace/ext/language_tools").setCompleters([]);
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableLiveAutocompletion: true,
        });

        // 模拟的本地数据库表名
        const mockDatabaseTables = {
            "db1": ["table1", "table2", "table3"],
            "db2": ["table4", "table5", "table6"]
        };

        // 定义自定义补全器
        const customCompleter = {
            getCompletions: function (editor, session, pos, prefix, callback) {
                var completions = [
                    {
                        caption: "user_name",
                        value: "user_name",
                        meta: "Field",
                        score: 1000,
                        docHTML: "<b>user_name</b>: The name of the user in the database."
                    },
                    {
                        caption: "user_email",
                        value: "user_email",
                        meta: "Field",
                        score: 900,
                        docHTML: "<b>user_email</b>: The email address of the user in the database."
                    },
                    {
                        caption: "SELECT",
                        value: "SELECT",
                        meta: "Keyword",
                        score: 1100,
                        docHTML: "<b>SELECT</b>: SQL statement to select data from a database."
                    },
                    {
                        caption: "FROM",
                        value: "FROM",
                        meta: "Keyword",
                        score: 1050,
                        docHTML: "<b>FROM</b>: SQL clause to specify the table to query data from."
                    },
                    {
                        caption: "addEventListener",
                        value: "element.addEventListener('event', function() {\n\t// code\n});",
                        meta: "function"
                    },
                    {
                        caption: "ddone",
                        value: "会当凌绝顶,一层五开之径",
                        meta: "模板"
                    }
                ];

                // 获取用户输入的数据库名
                const cursorPosition = editor.getCursorPosition();
                const currentLine = session.getLine(cursorPosition.row);

                // 匹配形如 dbName. 的模式
                const dbNameMatch = currentLine.match(/(\w+)\./);
                if (dbNameMatch) {
                    const dbName = dbNameMatch[1]; // 提取数据库名称
                    // 从本地模拟数据中获取表名
                    const tables = mockDatabaseTables[dbName] || [];
                    let tableCompletions = tables.map(tableName => ({
                        caption: tableName,
                        value: tableName,
                        meta: "table"
                    }));
                    callback(null, tableCompletions);
                } else {
                    callback(null, completions.map(function (c) {
                        return {
                            caption: c.caption,
                            value: c.value,
                            meta: c.meta,
                            score: c.score,
                            docHTML: c.docHTML
                        };
                    }));
                }
            }
        };

        // 将自定义补全器添加到 Ace Editor
        editor.completers = [customCompleter];


        // 获取前一个单词的函数
        function getPreviousWord(editor) {
            const cursorPosition = editor.getCursorPosition();
            const currentLine = editor.session.getLine(cursorPosition.row);
            const textBeforeCursor = currentLine.slice(0, cursorPosition.column);
            const words = textBeforeCursor.split(/\s+/);
            return words.length > 1 ? words[words.length - 2] : "";
        }

        // 获取光标前两个字符的函数
        function getPreviousTwoChars(editor) {
            const cursorPosition = editor.getCursorPosition();
            const currentLine = editor.session.getLine(cursorPosition.row);
            const textBeforeCursor = currentLine.slice(0, cursorPosition.column);
            return textBeforeCursor.slice(-2); // 返回光标前的两个字符
        }

        // 监听用户输入并保持之前的补全项
        // editor.commands.addCommand({
        //     name: "startAutocomplete",
        //     bindKey: { win: "Alt-Enter", mac: "Option-Enter" },
        //     exec: function(editor) {
        //         console.log("执行命令~~~~~~~~, 展开*****")
        //     }
        // });

        // 获取光标处字符的函数
        function getCharAtCursor(editor) {
            const cursorPosition = editor.getCursorPosition();
            const currentLine = editor.session.getLine(cursorPosition.row);
            return currentLine.charAt(cursorPosition.column); // 返回光标处的字符
        }

        // 监听内容更改事件
        editor.session.on('change', function (delta) {
            const cursorPosition = editor.getCursorPosition();
            const currentLine = editor.session.getLine(cursorPosition.row);

            // // 检查当前行是否为空或者只有空格
            // if (currentLine.trim() === "") {
            //     return; // 当前行为空或者只有空格，不触发自动补全提示
            // }

            if (getCharAtCursor(editor)==="\.") {
                // 手动触发自动补全提示
                setTimeout(() => {
                    editor.execCommand("startAutocomplete");
                }, 0);
            } else {
                if (editor.completer) {
                    editor.completer.detach();
                }
                console.log("当前提示词：" + editor.completer)
            }

            const cursorChar = getCharAtCursor(editor)
            console.log("当前光标字符：" + cursorChar)
            // if (editor.completer) {
            //     editor.completer.detach();
            // }


            // // 获取前一个单词
            // const previousWord = getPreviousWord(editor);
            // console.log("前一个单词:", previousWord);
            //
            // const previousTwoChars =getPreviousTwoChars(editor)
            // console.log("前两个字符" + previousTwoChars);
            // if (previousTwoChars === " *") {
            //     console.log("***************")
            // }

        });
    </script>
</body>
</html>
